#pragma once

#include <iostream>
#include <string>
#include "log.hpp"
#include "Init.hpp"

extern Log lg;
Init init;

class Task {
public:
    Task() {}
    Task(int sockfd, const std::string& clientip, const uint16_t& clientport) 
        :sockfd_(sockfd), clientip_(clientip), clientport_(clientport) {
    }

    void run() {
        char buffer[4096];
        //TCP是面向字节流的，如何保证读取到的数据是"一个" "完整"的报文
        ssize_t n = read(sockfd_, buffer, sizeof(buffer));
        if (n > 0) {
            // buffer[n-2] = 0;//使用telnet最后需要按回车还有换行符，去掉回车换行等
            buffer[n] = 0;
            std::cout << "client key# " << buffer << std::endl;
            std::string echo_string = init.translation(buffer);

            //假设服务器正准备写，客户端就关闭连接了。此时可能会造成类似管道的情况，
            //写入返回0，OS就结束写的这个进程。但服务器不能随便关闭，所以要对写入做判断
            //而且还需要处理SIG_PIPE信号，忽略处理
            n = write(sockfd_, echo_string.c_str(), echo_string.size());
            if (n < 0) {
                lg(Warning, "write error, errno:%d, errstring:%s", errno, strerror(errno));
            }
        }
        else if (n == 0) { //客户端退出
            lg(Info, "%s:%d quit, server close sockfd:%d", clientip_.c_str(), clientport_, sockfd_);
        }
        else {
            lg(Warning, "read error, sockfd:%d, client ip:%s, client port:%d", sockfd_, clientip_.c_str(), clientport_);
        }
        close(sockfd_);
    }

    void operator()() { run(); }


    ~Task() {}
private:
    int sockfd_;
    std::string clientip_;
    uint16_t clientport_;
};

